<template>
  <!-- 相关教程 -->
  <div class="app-container">
    <div class="filter-container">
      <k-button v-if="authorityHandle(159)" class="top-btn" value="新增" @click.native="addItemDialog" />
      <k-button v-if="authorityHandle(159)" class="top-btn" value="删除" @click.native="delItemData" />
    </div>
    <!--表格相关 -->
    <el-table
      ref="dragTable"
      :data="listData"
      fit
      border
      row-key="id"
      highlight-current-row
      style="width: 100%;border-radius:8px;"
      :header-cell-style="{background:'#F6F5FA',color:'#4E4F62'}"
      @selection-change="handleSelectionChange"
    >

      <el-table-column min-width="60px" type="selection" align="center" />
      <el-table-column prop="subject" min-width="150px" label="主题" align="center" show-overflow-tooltip />

      <el-table-column prop="createUser" min-width="150px" label="创建人" align="center" show-overflow-tooltip />
      <el-table-column min-width="200px" label="创建时间" align="center" show-overflow-tooltip>
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="开关" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :disabled="!authorityHandle(159)"
            active-color="#3b425d"
            inactive-color="#E9EBF2"
            active-text="开"
            inactive-text="关"
            :active-value="1"
            :inactive-value="0"
            @change="itemOnlineState($event,scope)"
          />
        </template>
      </el-table-column>
      <el-table-column min-width="200px" label="操作" align="center">
        <template slot-scope="scope">
          <div class="op-div">
            <k-button class="table-btn" value="修改/查看" @click.native="itemUpdateDialog(scope.row)" />
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加 弹窗 -->
    <k-dialog
      :show-hide.sync="addBox.showHide"
      :modal-append-to-body="false"
      :append-to-body="true"
      :title="textMap[dialogStatus]"
      class="addBox-dialog"
      :show-foot="false"
      :two-btn="authorityHandle(159)"
      @click="saveItemDataClick"
    >
      <el-form :model="addItemInfo" label-width="auto" class="form-modify">
        <el-form-item label="主题：">
          <el-input v-model="addItemInfo.subject" show-word-limit placeholder="请输入主题" />
        </el-form-item>

        <el-form-item label="内容：">
          <div class="dialog-ruleGuide">
            <input v-show="false" class="quill-img" type="file" @change="postFile($event)">
            <quill-editor
              ref="myQuillEditor"
              v-model.trim="addItemInfo.content"
              :options="editorOption"
              class="editer"
            />
          </div>
        </el-form-item>
      </el-form>
    </k-dialog>

  </div>
</template>

<script>
import Sortable from 'sortablejs'

import { getList, add, status, update, del, sort } from '@/api/settings/settings.js'
import { doUploadFile } from '@/api/upload/upload'
import { browserType } from '@/utils/validate'
export default {
  data() {
    return {
      editorOption: {
        placeholder: '请输入内容',
        modules: { // 富文本初始化
          'emoji-toolbar': true,
          'emoji-shortname': true,
          toolbar: {
            container: [
              ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
              ['blockquote', 'code-block'], // 引用，代码块
              [{
                header: 1
              }, {
                header: 2
              }], // 标题，键值对的形式；1、2表示字体大小
              [{
                list: 'ordered'
              }, {
                list: 'bullet'
              }], // 列表
              [{
                script: 'sub'
              }, {
                script: 'super'
              }], // 上下标
              [{
                indent: '-1'
              }, {
                indent: '+1'
              }], // 缩进
              [{
                direction: 'rtl'
              }], // 文本方向
              [{
                size: ['small', false, 'large', 'huge']
              }], // 字体大小
              [{
                header: [1, 2, 3, 4, 5, 6, false]
              }], // 几级标题
              [{
                color: []
              }, {
                background: []
              }], // 字体颜色，字体背景颜色
              [{
                font: []
              }], // 字体
              [{
                align: []
              }], // 对齐方式
              ['clean'], // 清除字体样式
              ['image', 'video'] // 上传图片、上传视频
            ],
            handlers: {
              image: function(value) {
                if (value) {
                  // 触发input框选择图片文件，并执行默认点击事件。
                  document.querySelector('.quill-img').click()
                } else {
                  this.quill.format('image', false)
                }
              }
            }
          },
          history: {
            delay: 1000,
            maxStack: 50,
            userOnly: false
          },
          imageDrop: true,
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        }
      },
      dialogStatus: 'create',
      textMap: {
        update: '修改',
        create: '创建'
      },

      timeValue: '',
      timeCotinue: '',

      addItemInfo: {
        id: '',
        subject: '', // 主题
        type: 2,
        content: ''// 内容
      },
      addBox: {
        showHide: false
      },

      listData: [],
      sortable: null,

      itemIds: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 等级福利列表页加载数据
    getList() {
      getList(2).then(res => {
        this.listData = res.data
        this.$nextTick(() => {
          if (this.authorityHandle(159)) {
            this.setSort()
          }
        })
      })
    },
    postFile(e) {
      const _this = this
      const file = e.target.files[0]
      const formData = new FormData()
      if (browserType('ie')) {
        formData.append('upLoadFile', file)
      } else {
        formData.set('upLoadFile', file)
      }
      doUploadFile(formData).then(res => {
        const quill = _this.$refs.myQuillEditor.quill // 获取富文本编辑器的编辑框、
        const img = new Image()
        img.src = res.data
        quill.focus() // 聚焦在上面
        quill.insertEmbed(quill.getSelection().index, 'image', img.src)
      })
    },
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll('.el-table__body-wrapper > table > tbody')[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost', // Class name for the drop placeholder,
        setData: function(dataTransfer) {
          // to avoid Firefox bug
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.listData.splice(evt.oldIndex, 1)[0]
          this.listData.splice(evt.newIndex, 0, targetRow)
          const ids = this.listData.map(item => item.id)
          sort({ ids: ids }).then(res => {
            this.getList()
          })
        }
      })
    },
    addItemDialog() {
      this.addBox.showHide = true
      this.dialogStatus = 'create'
      this.$resetForm(this.addItemInfo)
      this.addItemInfo.type = 2
    },
    itemUpdateDialog(row) {
      this.dialogStatus = 'update'
      this.addBox.showHide = true
      this.addItemInfo.id = row.id
      this.addItemInfo.subject = row.subject
      this.addItemInfo.content = row.content
      this.addItemInfo.type = 2
    },

    // 添加|修改
    saveItemDataClick() {
      if (!this.addItemInfo.subject || !this.addItemInfo.content) {
        this.$message.error('主题与内容必填')
        return
      }
      if (this.dialogStatus === 'create') {
        add(this.addItemInfo).then(res => {
          this.$message.success('操作成功')
          this.getList()
          this.$resetForm(this.addItemInfo)
        })
      } else {
        update(this.addItemInfo).then(res => {
          this.$message.success('操作成功')
          this.getList()
          this.$resetForm(this.addItemInfo)
        })
      }
      this.addBox.showHide = false
    },

    // 开关
    itemOnlineState(event, scope) {
      status({
        'id': scope.row.id,
        'status': scope.row.status
      }).then(res => {
        this.$message.success(res.message)
        this.getList()
      })
    },

    delItemData() {
      if (this.itemIds.length == 0) {
        this.$message.error('最少选择一项')
        return
      }
      this.$confirm('确定删除选中项么?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del({ ids: this.itemIds }).then(res => {
          if (res.data.success) {
            this.$message.success('操作成功')
            this.getList()
          } else {
            this.$message.error(res.data.msg)
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },

    // 选择项发生变化时会触发该事件
    handleSelectionChange(val) {
      const ids = val.map(item => item.id)
      this.itemIds = ids
    }
  }
}
</script>
<style>
	.sortable-ghost {
		opacity: .8;
		color: #fff !important;
		background: #3b425d !important;
	}
</style>
<style lang="scss" scoped>
	$mainColor:#3b425d; // 主色调
	$disabledColor: #909399; //禁用色
	$hoverColor:#1D143C; // 鼠标停留主色调浅色

	::v-deep .el-select .el-input.is-focus .el-input__inner {
		border-color: $mainColor;
	}

	::v-deep .el-input__inner:focus {
		border-color: $mainColor;
	}

	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}

	.price-input {
		width: 70px;
	}

	.addBox-dialog {
		::v-deep .el-dialog__body {
			padding: 10px 80px;
		}

		::v-deep .image-slot {
			display: flex;
			justify-content: center;
			align-items: center;
			width: 100%;
			height: 100%;
			background: #f5f7fa;
			color: #909399;
			font-size: 40px;
		}

		::v-deep .el-textarea__inner:focus {
			outline: 0;
			border-color: $mainColor;
		}
	}

	.upload-btn {
		font-size: 14px;
		color: #ffffff;
	}

	.editer {
		border-radius: 8px;
		float: left;
		box-sizing: border-box;
		color: #606266;

		::v-deep .ql-container {
			height: 440px;
			border-radius: 0px 0px 8px 8px;
		}

		::v-deep .ql-toolbar.ql-snow {
			border-radius: 8px 8px 0px 0px;
		}
	}

	.dialog-warningSetting {
		::v-deep.el-input {
			width: 110px;
		}

		.price-input {
			width: 100px;
		}

		.el-icon {

			&-circle-plus,
			&-remove {
				font-size: 22px;
				color: #3b425d;
				margin-left: 10px;

			}
		}

		ul {
			list-style-type: none;
			margin-top: 20px;
			padding: 0;

			li {
				margin: 0 0 30px 0px;
				display: flex;
				flex-direction: row;
				align-items: center;

				i {
					color: #D1D5DD;
				}
			}
		}

		.warning-title {
			font-size: 16px;
			color: #14162E;

			&-right {
				font-size: 16px;
				color: #14162E;
				margin-left: 80px;
			}

			&-right2 {
				font-size: 16px;
				color: #14162E;
				margin-left: 20px;
			}
		}
	}

	.filter-container {
		width: 100%;
		height: 48px;
		line-height: 48px;
		margin-bottom: 30px;

		.filter-item {
			display: inline-block;
			vertical-align: middle;
			margin-bottom: 10px;
		}

		.top-btn {
			font-size: 14px;
			color: #ffffff;
		}

		.kInput {
			position: absolute;
			right: 20px;
		}
	}

	.chargeform {
		display: flex;
		flex-direction: row;
	}
</style>
